<?php

namespace App\Http\Models;

use Illuminate\Support\Facades\Auth;

//商品纠错表
class GoodsCorrection extends BaseModel
{
    protected $table = 'goods_correction';
    protected $guarded = [];

    //对应商品表
    public function goods()
    {
        return $this->belongsTo(Goods::class, 'gid');
    }

    //对应user表
    public function user()
    {
        return $this->belongsTo(User::class, 'userid', 'id');
    }

    public static function get_type()
    {
        return [
            '0' => '价格问题',
            '1' => '优惠券问题',
            '2' => '佣金问题',
            '3' => '商品/售后问题',
            '4' => '其他',
            '5' => '商品已下架,平台未下架'
        ];
    }

    public function setStateAttribute($state)
    {
        $this->attributes['state'] = $state == 'on' ? 1 : ($state == 'off' ? 0 : $state);
    }

    /**
     * 更新所有的商品中的纠错信息
     * @param $gid 商品id
     * @param $error_type 纠错类型
     * @return mixed
     */
    public static function updateErrorStatus($gid, $error_type, $goods_status=0)
    {
        if (!is_array($error_type)) {
            return false;
        }
        foreach ($error_type as $k => $v) {
            if (is_null($v))
                unset($error_type[$k]);
        }
        $types = array_values($error_type);
        if (count($types) > 0) {
            Goods::updateError($gid, 0);
            $all_error = self::whereIn('type', $types)->where(['gid' => $gid])->get();
            foreach ($all_error as $key => $value) {
                StatisticsGoodsInfo::updateStatisticsGoods($value->id, 3, 1, 1, $value->created_at,0 ,false, 1);
            }
            $error_num = self::whereIn('type', $types)->where(['gid' => $gid])->update(['state' => 1]);
            return $error_num;
        } else {
            return true;
        }
    }

    public static function getErrorType()
    {
        //0价格问题，1优惠券问题，2佣金问题，3商品/售后问题，4其他
        return [
            '1' => '优惠券问题',
            '2' => '佣金问题',
            '3' => '商品/售后问题',
            '4' => '其他',
            '0' => '价格问题',
        ];
    }

    /**
     * 获取一个商品存在的错误类型
     * @param $goodsid
     * @return array
     */
    public static function getGoodsErrorType($goodsid)
    {
        $is_set_error_type = GoodsCorrection::select('type')->where(['gid' => $goodsid])->get();
        if ($is_set_error_type) {
            $is_set_error_type = $is_set_error_type->toArray();
            if (count($is_set_error_type) > 0) {
                $is_set_error_type = array_values(array_unique(array_column($is_set_error_type, 'type')));
            }
        } else {
            $is_set_error_type = [];
        }
        return $is_set_error_type;
    }

    public static function getGoodsError($gid)
    {
        return self::where(['gid' => $gid, 'state' => 0])->first();
    }

}